package com.holyn.guofang.view.distinguish;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.BrandItemInfoWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.distinguish.DistinguishContract;
import com.holyn.guofang.presenter.distinguish.DistinguishPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.popupwindow.PopupResultListFilter;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/7/16.
 */

public class SearchResultListActivity extends BaseActivity implements BaseView, DistinguishContract.BrandItemView
        , OnLoadmoreListener, PopupResultListFilter.OnFilterClickLIstener{
    private static final int REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID_FIRST = 0x0001;
    private static final int REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID_MORE = 0x0002;

    public static final String INTENT_KEY_BRAND_ITEM_INFO_WO = "INTENT_KEY_BrandItemInfoWo";
    public static final String INTENT_KEY_TASK_ID = "INTENT_KEY_TASK_ID";

    @BindView(R.id.tv_sort_type_0)
    TextView tvSortType0;
    @BindView(R.id.tv_sort_type_1)
    TextView tvSortType1;
    @BindView(R.id.tv_sort_type_2)
    TextView tvSortType2;
    @BindView(R.id.tv_sort_type_3)
    TextView tvSortType3;
    @BindView(R.id.tv_sort_type_more)
    TextView tvSortTypeMore;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.tv_count)
    TextView tvCount;

    private DistinguishContract.Presenter presenter;

    private BrandItemInfoWo brandItemInfoWo;
    private MyListAdapter myListAdapter;
    private RecycleViewDivider recycleViewDivider;
    private MyGridAdapter myGridAdapter;
    private GridSpacingItemDecoration gridSpacingItemDecoration;

    private boolean curIsShowListView = true;

    private PopupResultListFilter popupResultListFilter;

    Integer TaskID;
    String SortType;
    Integer BeginRow = 1;
    Integer EndRow = 20;

    private Integer pageSize = 20;

    public static void start(Activity activity, BrandItemInfoWo brandItemInfoWo, Integer TaskID){
        Intent intent = new Intent(activity, SearchResultListActivity.class);
        intent.putExtra(INTENT_KEY_BRAND_ITEM_INFO_WO, brandItemInfoWo);
        intent.putExtra(INTENT_KEY_TASK_ID, TaskID);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_search_result_list;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbarMenuRight("查询结果", true, "切换视图", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                curIsShowListView = !curIsShowListView;
                if (curIsShowListView){
                    initListView();
                } else {
                    initGridView();
                }
            }
        });

        initData();

        popupResultListFilter = new PopupResultListFilter(this);
        popupResultListFilter.setOnFilterClickLIstener(this);

        recycleViewDivider = new RecycleViewDivider(SearchResultListActivity.this, LinearLayoutManager.VERTICAL);
        gridSpacingItemDecoration = new GridSpacingItemDecoration(3, 4, false);

        presenter = new DistinguishPresenter(this);
        presenter.addBrandItemViewListener(this);

        initListView();
        initCountView();

        refreshLayout.setOnLoadmoreListener(this);

        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                ClassicsFooter footer = new ClassicsFooter(context);
                footer.setBackgroundResource(android.R.color.white);
                footer.setSpinnerStyle(SpinnerStyle.Scale);//设置为拉伸模式
                return footer;//指定为经典Footer，默认是 BallPulseFooter
            }
        });
    }

    private void initData(){
        brandItemInfoWo = (BrandItemInfoWo) getIntent().getSerializableExtra(INTENT_KEY_BRAND_ITEM_INFO_WO);
        brandItemInfoWo.getData().getICount();
        TaskID = getIntent().getIntExtra(INTENT_KEY_TASK_ID, 0);
    }

    private void initListView(){
        myListAdapter = new MyListAdapter(brandItemInfoWo.getData().getResult());
//        myListAdapter.setOnLoadMoreListener(this, rvList);
        rvList.setLayoutManager(new LinearLayoutManager(SearchResultListActivity.this));
        rvList.removeItemDecoration(gridSpacingItemDecoration);
        rvList.addItemDecoration(recycleViewDivider);
        rvList.setAdapter(myListAdapter);

        myListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                BrandItemInfoWo.DataBean.ResultBean resultBean = brandItemInfoWo.getData().getResult().get(position);
                SearchResultDetailActvity.start(SearchResultListActivity.this, resultBean.getMarkNo(), resultBean.getMarkClass());
            }
        });
    }

    private void initGridView(){
        myGridAdapter = new MyGridAdapter(brandItemInfoWo.getData().getResult());
//        myGridAdapter.setOnLoadMoreListener(this, rvList);
        rvList.setLayoutManager(new GridLayoutManager(SearchResultListActivity.this, 3));
        rvList.removeItemDecoration(recycleViewDivider);
        rvList.addItemDecoration(gridSpacingItemDecoration);
        rvList.setAdapter(myGridAdapter);

        myGridAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                BrandItemInfoWo.DataBean.ResultBean resultBean = brandItemInfoWo.getData().getResult().get(position);
                SearchResultDetailActvity.start(SearchResultListActivity.this, resultBean.getMarkNo(), resultBean.getMarkClass());
            }
        });
    }

    private void initCountView(){
        tvCount.setText("符合记录的共"+brandItemInfoWo.getData().getICount()+"条数据，当前显示前"+brandItemInfoWo.getData().getResult().size()+"条数据");
    }

    @OnClick({R.id.tv_sort_type_0, R.id.tv_sort_type_1, R.id.tv_sort_type_2, R.id.tv_sort_type_3, R.id.tv_sort_type_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sort_type_0:
                postSearchResultByTaskId("0", 1, pageSize, false);
                break;
            case R.id.tv_sort_type_1:
                postSearchResultByTaskId("1", 1, pageSize, false);
                break;
            case R.id.tv_sort_type_2:
                postSearchResultByTaskId("2", 1, pageSize, false);
                break;
            case R.id.tv_sort_type_3:
                postSearchResultByTaskId("3", 1, pageSize, false);
                break;
            case R.id.tv_sort_type_more:
                popupResultListFilter.showPopupWindow(tvSortTypeMore);
                break;
        }
    }

    @Override
    public void onFilterClick(String SortType) {
        postSearchResultByTaskId(SortType, 1, pageSize, false);
    }

    private void postSearchResultByTaskId(String SortType, Integer BeginRow, Integer EndRow, boolean isLoadMOre){
        this.SortType = SortType;
        this.BeginRow = BeginRow;
        this.EndRow = EndRow;
        if (isLoadMOre){
            presenter.postSearchResultByTaskID(REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID_MORE, TaskID, SortType, BeginRow, EndRow);
        } else {
            refreshLayout.setLoadmoreFinished(false);
            presenter.postSearchResultByTaskID(REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID_FIRST, TaskID, SortType, BeginRow, EndRow);
        }

    }

    @Override
    public void requestStart(Integer requestAction) {
        LogUtils.d("requestStart....");
        if (requestAction == REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID_FIRST){
            showLoadingDialog();
        }
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        LogUtils.d("requestError...."+e);
        closeLoadingDialog();
        refreshLayout.finishLoadmore();

        if (e.toString().contains("SocketTimeoutException")){
            toastMsg("请求超时");
        }
        if (e.toString().contains("JsonException")){
            toastMsg("返回数据格式有误");
        }

    }

    @Override
    public void requestComplete(Integer requestAction) {
        LogUtils.d("requestComplete...."+curIsShowListView);
        closeLoadingDialog();
        refreshLayout.finishLoadmore();
    }

    @Override
    public void responseSuccess(Integer requestAction, BrandItemInfoWo brandItemInfoWo) {
        LogUtils.d("responseSuccess....");
        if (brandItemInfoWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            if (EndRow - pageSize >= brandItemInfoWo.getData().getICount()){
                toastMsg("数据全部加载完毕");
                refreshLayout.setLoadmoreFinished(true);
            } else {
                if (requestAction == REQUEST_ACTION_POST_SEARCH_REULT_BY_TASK_ID_MORE){
                    if (brandItemInfoWo.getData().getResult() == null){
                        toastMsg("数据返回为空");
                    } else if (brandItemInfoWo.getData().getResult().size() == 0){
                        toastMsg("数据返回为空");
                    } else {
//                        this.brandItemInfoWo.getData().getResult().addAll(brandItemInfoWo.getData().getResult());
                        if (curIsShowListView){
                            myListAdapter.addData(brandItemInfoWo.getData().getResult());
                        } else {
                            myGridAdapter.addData(brandItemInfoWo.getData().getResult());
                        }
                    }

                } else {
                    cloneBrandItemInfoWo(brandItemInfoWo, this.brandItemInfoWo);
                    if (curIsShowListView){
                        myListAdapter.notifyDataSetChanged();
                    } else {
                        myGridAdapter.notifyDataSetChanged();
                    }
                }

                initCountView();
            }
        } else {
            if (TextUtils.isEmpty(brandItemInfoWo.getErr())){
                toastMsg("获取数据失败！");
            } else {
                toastMsg(brandItemInfoWo.getErr());
            }
        }
    }

//    @Override
//    public void onLoadMoreRequested() {
//        LogUtils.d("加载更多onLoadMoreRequested....");
//        postSearchResultByTaskId(SortType, BeginRow+pageSize, EndRow+pageSize, true);
//    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        LogUtils.d("加载更多onLoadmore....");
        postSearchResultByTaskId(SortType, BeginRow+pageSize, EndRow+pageSize, true);
    }

    private void cloneBrandItemInfoWo(BrandItemInfoWo from, BrandItemInfoWo to){
        to.setStatus(from.getStatus());
        to.setSrcImgID(from.getSrcImgID());
        to.setUrl(from.getUrl());
        to.getData().setFinishTime(from.getData().getFinishTime());
        to.getData().setICount(from.getData().getICount());
        to.getData().setState(from.getData().getState());
        to.getData().setSubTime(from.getData().getSubTime());
        to.getData().getResult().clear();
        to.getData().getResult().addAll(from.getData().getResult());
    }

    private class MyListAdapter extends BaseQuickAdapter<BrandItemInfoWo.DataBean.ResultBean, BaseViewHolder>{

        public MyListAdapter(@Nullable List<BrandItemInfoWo.DataBean.ResultBean> data) {
            super(R.layout.item_search_result_list, data);
        }

        @Override

        protected void convert(BaseViewHolder helper, BrandItemInfoWo.DataBean.ResultBean item) {
            ImageView ivHeard = helper.getView(R.id.iv_heard);
            Glide.with(SearchResultListActivity.this)
                    .load(item.getMarkImagePath())
//                    .error(R.drawable.ic_empty_image)
                    .into(ivHeard);
            String registerPublishDate = "";
            if (!TextUtils.isEmpty(item.getRegisterPublishDate())){
                registerPublishDate = item.getRegisterPublishDate();
            }
            String result = "第"+item.getMarkNo()+"号  第"+item.getMarkClass()+"类"
                    +"\n注册人："+item.getHolderNameCn()
                    +"\n申请日期："+item.getApplicationDate()
                    +"\n注册日期："+registerPublishDate;
            String isValid = item.getIsValid();
            result = result + "\n状态："+isValid;
            helper.setText(R.id.tv_content, result);
        }
    }

    private class MyGridAdapter extends BaseQuickAdapter<BrandItemInfoWo.DataBean.ResultBean, BaseViewHolder>{
        public MyGridAdapter(@Nullable List<BrandItemInfoWo.DataBean.ResultBean> data) {
            super(R.layout.item_search_result_grid, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, BrandItemInfoWo.DataBean.ResultBean item) {
            ImageView ivHeard = helper.getView(R.id.iv_heard);
            Glide.with(SearchResultListActivity.this)
                    .load(item.getMarkImagePath())
//                    .error(R.drawable.ic_empty_image)
                    .into(ivHeard);
            helper.setText(R.id.tv_content, item.getMarkClass()+"类"+item.getMarkNo());
        }
    }
}
